#include "terminaldialog.h"
#include "ui_terminaldialog.h"
#include<QDebug>

TerminalDialog::TerminalDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TerminalDialog)
{
    ui->setupUi(this);
    process = new QProcess(parent);
    connect(process , SIGNAL(readyReadStandardOutput()) , this , SLOT(onReadStandardOutput()));
    connect(process , SIGNAL(readyReadStandardError()) , this , SLOT(onReadStandardError()));
    process->start("pkexec /bin/bash");
    process->waitForStarted();
    QStringList env = QProcess::systemEnvironment();
    for(int i=0;i<env.size();i++){
        QString e = env.at(i);
        process->write(QString("export %1\n").arg(e).toUtf8());
    }
}

TerminalDialog::~TerminalDialog()
{
    delete ui;
}

void TerminalDialog::on_pushButton_clicked()
{
    process->write("filezilla &\n");
}

void TerminalDialog::onReadStandardOutput()
{
    QString outStr = QString::fromUtf8(process->readAllStandardOutput().data());
    qDebug() << QString("stdout: %1").arg(outStr);
    ui->textBrowser->append(outStr);
}

void TerminalDialog::onReadStandardError()
{
    QString errStr = QString::fromUtf8(process->readAllStandardError().data());
    qDebug() << QString("stderr: %1").arg(errStr);
    ui->textBrowser->append(errStr);

}

void TerminalDialog::on_pushButton_2_clicked()
{
    process->write("ps aux | grep filezilla | grep -v grep | awk '{print $2}' | xargs -i kill {}\n");
    process->write("exit\n");
    process->waitForFinished();
}
